package com.example.poc.user;

import java.util.HashSet;
import java.util.Set;

import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@Configuration
class UserDataLoader {
  @Bean
  CommandLineRunner initUsers(UserRepository userRepository) {
    return args -> {
      if (userRepository.count() == 0) {
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder(10);
        Set<UserRole> roles = new HashSet<>();
        UserRole userRole = new UserRole();
        userRole.setRoleName(RoleName.ROLE_USER);
        UserRole adminRole = new UserRole();
        adminRole.setRoleName(RoleName.ROLE_ADMIN);
        if (!userRepository.findById(1L).isPresent()) {
          User user = new User();
          user.setEmail("user@somewhere.com");
          user.setEnabled(true);
          user.setLocked(false);
          user.setUsername("user");
          user.setPassword(bCryptPasswordEncoder.encode("resu"));
          roles.add(userRole);
          user.setRoles(roles);
          userRepository.save(user);
        }
        if (!userRepository.findById(2L).isPresent()) {
          User admin = new User();
          admin.setEmail("admin@somewhere.com");
          admin.setEnabled(true);
          admin.setLocked(false);
          admin.setUsername("admin");
          admin.setPassword(bCryptPasswordEncoder.encode("nimda"));
          roles.add(adminRole);
          admin.setRoles(roles);
          userRepository.save(admin);
        }
      }
    };
  }

}
